package cn.hchaojie.ssm.aspect;

import java.lang.reflect.Executable;

import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import cn.hchaojie.ssm.exception.ServiceException;

@ControllerAdvice
public class DefaultExeptionHandler {
	private Logger logger = LoggerFactory.getLogger(DefaultExeptionHandler.class);
	
	/** 处理数据库完整性约束的异常 */
	@ExceptionHandler(DataIntegrityViolationException.class)
	public String handleException(DataIntegrityViolationException e, Model model) {
		System.out.println("捕获到数据完整性异常：" + e.getMessage());
		

		model.addAttribute("errorCode", "20001");
		model.addAttribute("errorMessage", "服务器内部出错，请稍后重试！");
		
		// 记录错误到日志文件
		logger.error("1数据库访问异常！", e);
		
		logger.debug("2数据库访问异常。。。");
		logger.info("3数据库访问异常。。。");
		logger.warn("3数据库访问异常。。。");
		
		return "/error/500";
	}
	
	/** 处理service异常 */
	@ExceptionHandler(ServiceException.class)
	public String handleServiceException(ServiceException e, Model model) {
		model.addAttribute("errorCode", e.getCode());
		model.addAttribute("errorMessage", e.getMessage());
		
		// 记录错误到日志文件
		logger.error("service异常", e);
		
		return "/error/500";
	}
	
	/** 处理文件上传的错 */
	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public String handleFileUploadException(MaxUploadSizeExceededException e, Model model) {
		model.addAttribute("errorCode", "20003");
		model.addAttribute("errorMessage", "文件大小超过了限制, 限定的大小为：" + e.getMaxUploadSize());
		
		return "/error/500";
	}
	
	/**
	 * 处理其它异常
	 * 
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public String handleGeneralException(Exception e) {
		logger.error("未知的服务器异常", e);
		
		return "/error/500";
	}
}
